<template>
    <div class="map-container">
        <div id="gisMap" class="gis-map"></div>
    </div>
</template>
<script>
export default {
    props:['path'],
    name: "gisMap",
    data() {
        return {
            map:null,
            polygon:null,
            apiKeys: [
                '5c68d0d10d0fa048192d148108ba00b9', // 项目原本key
                '8b94e951fdd8ef3dce4b5153362e8f08', // sameki key
                '027fa055be0f270ee79ea246b7457ce6', // 原链企业账号key
                '7f398b21619c5b414899d630b388100b', // xls key
                '41252f44578a99fda1a999538d537df3', // duan key
            ],
            currentApiKeyIndex: 0, // 当前使用的key索引
            maxRetries: 3, // 最大重试次数
            retryCount:0,//重试次数
            TK_KEY:'',//当前key
        }
    },
    mounted() {
        this.initLeaftMap();
    },
    methods:{
        initLeaftMap() {
            if (this.map) this.map.remove();
            this.map = null;
            //限制地图的拖动范围是正负90到正负180，这样才合理。
            var corner1 = L.latLng(-90, -180); //设置左上角经纬度
            var corner2 = L.latLng(90, 180);	//设置右下点经纬度
            var bounds = L.latLngBounds(corner1, corner2); //构建视图限制范
            //自定义leaflet天地图经纬度坐标
            //设置地图相关初始配置
            this.map = L.map("gisMap", {
                minZoom: 2,
                maxZoom: 14,
                preferCanvas:true,
                zoom:11, //初始地图缩放级别
                crs: L.CRS.EPSG4326,//设置坐标系4326
                scrollWheelZoom: true, //默认开启鼠标滚轮缩放
                zoomControl: true, //禁用 + - 按钮
                doubleClickZoom: false, // 禁用双击放大
                attributionControl: false, // 移除右下角leaflet标识
            });
            this.TK_KEY = this.apiKeys[this.currentApiKeyIndex];

            // 底图
            //vec_c 交通标记
            const vec_c = 'http://{s}.tianditu.gov.cn/vec_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk='
            //cta_c 地名地点标记
            const cta_c = 'http://{s}.tianditu.gov.cn/cta_c/wmts?layer=cta&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=';
            //img_c 卫星地图
            const img_c = 'http://{s}.tianditu.gov.cn/img_c/wmts?layer=img&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=';
            let img_cLayer = L.tileLayer(img_c + this.TK_KEY, {
                    maxZoom: 18,
                    tileSize: 256,
                    zoomOffset: 1,
                    subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
                }, { noWrap: false }).addTo(this.map);
            let cta_cLayer = L.tileLayer(cta_c + this.TK_KEY, {
                    maxZoom: 18,
                    tileSize: 256,
                    zoomOffset: 1,
                    subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
                }, { noWrap: false }).addTo(this.map);
            this.drawArea()
            img_cLayer.on('tileerror', () => {
                    console.log('检测到图层加载失败，尝试使用新的key加载地图图层')
                    //删除当前加载失败的图层
                    this.map.removeLayer(cta_cLayer);
                    this.map.removeLayer(img_cLayer);
                    setTimeout(() => {
                        console.log(`当前尝试次数：${this.retryCount + 1}次,已删除当前加载失败的图层，尝试加载新图层中...`)
                        this.changeApiKey();
                    }, 1000)
                });
        },
        changeApiKey() {
            this.currentApiKeyIndex = (this.currentApiKeyIndex + 1) % this.apiKeys.length;
            if (this.currentApiKeyIndex > this.apiKeys.length - 1) {
                console.log('已遍历完key,正在尝试寻找可用的key')
                //重置使用key组的第一个key
                this.currentApiKeyIndex = 0;
            }
            //最大尝试次数超过key组长度或key组不足3个则不再尝试
            this.retryCount++
            if (this.retryCount >= (this.maxRetries = this.apiKeys.length >= 3 ? this.apiKeys.length : this.maxRetries)) {
                setTimeout(() => {
                    console.log('超过尝试次数，但均无法加载地图，请联系管理员')
                }, 3000)
                return
            }
            this.TK_KEY = this.apiKeys[this.currentApiKeyIndex];
            console.log(`Switched to API key: ${this.TK_KEY}`);
            setTimeout(() => {
                console.log('已成功切换key,正在尝试重新加载地图')
                this.initLeaftMap()

            }, 4000)
        },
        drawArea(){
            // if(this.polygon){
            //     this.polygon.remove();
            // }
            console.log('当前坐标：',this.path)
            this.polygon = L.polygon(this.path, {
                fillColor: 'rgb(2,152,222)',
                fillOpacity: 0.6,
                opacity: 0,
            }).addTo(this.map);
            this.map.fitBounds(this.polygon.getBounds());

            // 获取多边形的中心点坐标
            const centerLatLng = this.polygon.getBounds().getCenter();
            // 创建自定义图标
            const customIcon = L.icon({
                iconUrl: 'https://img0.baidu.com/it/u=3844691602,2621532101&fm=253&fmt=auto&app=138&f=PNG?w=500&h=785', // 确保路径正确
                iconSize: [25, 35], // 图标的大小
                iconAnchor: [12, 19], // 图标锚点
                popupAnchor: [0, -19] // 弹出框锚点
            });
            L.marker(centerLatLng,{
                icon:customIcon,
            }).addTo(this.map)
                .bindPopup('坐标: ' + centerLatLng.toString())
                .openPopup();
        },

    }
}
</script>
<style scoped lang="less">
.map-container{
    width: 100%;
    height: 300px;
    .gis-map{
        width: 100%;
        height: 100%;
    }
}
</style>
